#include "myCAN\myCAN.h"


/*
 * @brief  CAN初始化函数
 * @说明：内部调用
 * @参数: 无
 * @函数返回值：无
 * @日期: 2025-1-14
 */
static void myCAN_Init(void)
{
	
}

/*
 * @brief  CAN发送函数
 * @param  hcan: CAN句柄
 * @param  StdId: 标准帧ID
 * @param  pData: 数据指针
 * @param  Len: 数据长度
 * @作者: 跳河轻生的鱼
 * @日期: 2024-12-14
 */
static void MyCAN_Transmit(uint32_t ID,uint8_t *Data, uint8_t Length)
{
#ifdef __HAL
	CAN_TxHeaderTypeDef TxHeader;
    uint32_t Timeout = 0;
    uint32_t pTxMailbox;
    TxHeader.StdId = ID;                                    // 标准帧ID
    TxHeader.RTR = CAN_RTR_DATA;                               // 数据帧
    TxHeader.IDE = CAN_ID_STD;                                 // 标准帧
    TxHeader.DLC = Length;                                        // 数据长度
    while(HAL_CAN_AddTxMessage(&hcan, &TxHeader, Data, &pTxMailbox) != HAL_OK)
    {
        Timeout++;
        /* 超时处理 */
        if(Timeout > 100000)//大概7200为100us
        {
            break;
        }
    }
	
#else
	CanTxMsg TxMessage;
	TxMessage.StdId = ID;
	TxMessage.ExtId = ID;
	TxMessage.IDE = CAN_Id_Standard;		//CAN_ID_STD
	TxMessage.RTR = CAN_RTR_Data;
	TxMessage.DLC = Length;
	for (uint8_t i = 0; i < Length; i ++)
	{
		TxMessage.Data[i] = Data[i];
	}
	
	uint8_t TransmitMailbox = CAN_Transmit(CAN1, &TxMessage);
	
	uint32_t Timeout = 0;
	while (CAN_TransmitStatus(CAN1, TransmitMailbox) != CAN_TxStatus_Ok)
	{
		Timeout ++;
		if (Timeout > 100000)
		{
			break;
		}
	}
	
#endif

}


static uint8_t MyCAN_ReceiveFlag(void)
{
	
#ifdef __HAL
	uint32_t fifoLevel = HAL_CAN_GetRxFifoFillLevel(&hcan, CAN_RX_FIFO0);  // 获取 FIFO0 的接收消息数量
	if (fifoLevel>0)  // 检查 FIFO0 是否有接收到的消息
	{
		return 1;
	}
	return 0;
#else
	if (CAN_MessagePending(CAN1, CAN_FIFO0) > 0)
	{
		return 1;
	}
	return 0;
#endif
	
}

static void MyCAN_Receive(uint32_t *ID, uint8_t *Data, uint8_t *Length)
{
#ifdef __HAL
	CAN_RxHeaderTypeDef RxHeader;
    if (HAL_CAN_GetRxMessage(&hcan, CAN_RX_FIFO0, &RxHeader, Data) == HAL_OK)
    {
		// 处理接收到的消息
        // RxHeader 包含消息头信息（如ID、DLC等）
		*ID = (RxHeader.IDE == CAN_ID_STD) ? RxHeader.StdId : RxHeader.ExtId;
        // RxData 是接收到的数据
        *Length = RxHeader.DLC;
	}

#else
	
	CanRxMsg RxMessage;
	CAN_Receive(CAN1, CAN_FIFO0, &RxMessage);
	
	if (RxMessage.IDE == CAN_Id_Standard)
	{
		*ID = RxMessage.StdId;
	}
	else
	{
		*ID = RxMessage.ExtId;
	}
	
	if (RxMessage.RTR == CAN_RTR_Data)
	{
		*Length = RxMessage.DLC;
		for (uint8_t i = 0; i < *Length; i ++)
		{
			Data[i] = RxMessage.Data[i];
		}
	}
	else
	{
		//...
	}
#endif

}


/*  定义CAN类的具体实现
 */
static struct CAN_Class myCanClass = {
	.init = myCAN_Init,
	.Transmit = MyCAN_Transmit,
	.Receive = MyCAN_Receive,
	.getFlag = MyCAN_ReceiveFlag,
};


/* 
 * 获取CAN类的实现句柄
 */
struct CAN_Class *get_CAN_Class(void)
{
	return &myCanClass;
}



